package com.nova.android.tvlauncher.ext

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.widget.TextView
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleCoroutineScope
import com.nova.android.tvlauncher.ui.activity.atv.CommonRightPanelAtvActivity
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.currentActivity
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.startKtxActivity
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import android.graphics.Bitmap
import android.graphics.drawable.ColorDrawable
import android.widget.ImageView
import androidx.palette.graphics.Palette
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.bumptech.glide.request.transition.Transition
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.apkinstall.isSameVersionInstalled
import com.nova.android.tvlauncher.bean.atv_bean.ChanelData
import com.nova.android.tvlauncher.bean.atv_bean.CusChanelDto
import com.nova.android.tvlauncher.bean.atv_bean.HomeChannelDto
import com.nova.android.tvlauncher.bean.atv_bean.HomeParentDto
import com.nova.android.tvlauncher.download.AppTask
import com.nova.android.tvlauncher.download.AppTaskStatus
import com.nova.android.tvlauncher.ui.activity.atv.CommonPanelActivity
import com.nova.android.tvlauncher.utils.TvRepository
import com_github_lib_base.APPSTORE_APP_ID
import com_github_lib_base.ext.getAppNameWithCache
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import java.io.File
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.forEach
import kotlin.collections.get

fun ImageView.loadWithBackground(imageUrl: String) {
    Glide.with(this.context)
        .asBitmap()
        .load(imageUrl)
        .into(object : BitmapImageViewTarget(this) {
            override fun onResourceReady(
                resource: Bitmap,
                transition: Transition<in Bitmap>?
            ) {
                // 提取主色
                Palette.from(resource).generate { palette ->
                    val dominantColor = palette?.getDominantColor(0xFF000000.toInt())
                    this@loadWithBackground.background = ColorDrawable(dominantColor ?: 0xFF000000.toInt())
                }

                // 设置图片等比居中
                this@loadWithBackground.scaleType = ImageView.ScaleType.CENTER_INSIDE
                this@loadWithBackground.setImageBitmap(resource)
            }
        })
}


// 顶层变量存储 Job
private var timeJob: Job? = null

fun TextView?.showCurrentTime(lifecycleScope: LifecycleCoroutineScope) {
    if (this == null) return

    // 取消现有的协程任务
    timeJob?.cancel()

    // 启动新的协程任务
    timeJob = lifecycleScope.launch {
        var previousTime: String? = null
        while (true) {
            val currentTime = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())
            if (currentTime != previousTime) {
                this@showCurrentTime.text = currentTime
                previousTime = currentTime
            }
            delay(1000)
        }

    }
}

fun String.launchCommonRightPanelAtvActivity(){
    val context = currentActivity as FragmentActivity?
    context?.startKtxActivity<CommonRightPanelAtvActivity>(
        values = arrayOf(
            Pair(
                CommonRightPanelAtvActivity.Companion.TYPE,
                this
            )
        )
    )
}


fun MutableList<ApplicationInfo>.getInstalledApps() = run {

    val appInfo = currentActivity?.getNonSystemApps()
    appInfo?.forEachIndexed { index, it ->
        it.applicationInfo?.let {app->
            when {
                app.packageName.isSystemApp() -> {
                    if (
                        app.packageName.contains("vending") ||
                        app.packageName.contains("chrome") ||
                        app.packageName.contains("youtube")
                    ) {
                        this.add(app)
                    }
                }
                else -> {
                    this.add(app)
                }
            }
        }

    }
    this
}

fun Activity.getNonSystemApps() = run {
    val packageManager = this.packageManager
    val installedApps = packageManager.getInstalledPackages(0)
    installedApps.filter { appInfo ->
        packageManager.getLaunchIntentForPackage(appInfo.packageName) != null
    }
}

fun String.isSystemApp(): Boolean {
    return try {
        val applicationInfo = appContext.packageManager.getApplicationInfo(this, 0)
        (applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0 ||
                (applicationInfo.flags and ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0
    } catch (e: PackageManager.NameNotFoundException) {
        false
    }
}

fun String.getAppIcon(): Drawable? {
    return try {
        val packageManager = appContext.packageManager
        val applicationInfo = packageManager.getApplicationInfo(this, 0)
        val resources = packageManager.getResourcesForApplication(applicationInfo)

        // 尝试获取 bannerres 资源
        val bannerResId = applicationInfo.banner
        if (bannerResId != 0) {
            applicationInfo.loadBanner(packageManager)
            //resources.getDrawable(bannerResId, null)
        } else {
            // 如果没有找到 bannerres 资源，则获取默认的 icon 资源
            packageManager.getApplicationIcon(applicationInfo)
        }
    } catch (e: PackageManager.NameNotFoundException) {
        // 如果包名无法找到，返回 null
        null
    }
}

fun ApplicationInfo.appName() = appContext.packageManager.getApplicationLabel(this).toString()

fun String.openAppInStore(context: Context) {
    // 先尝试跳转到 CHIHI App Store
    val chihiAppStorePackageName = APPSTORE_APP_ID

    if (chihiAppStorePackageName != null) {
        try {
            chihiAppStorePackageName.openApp()
            return // 如果成功跳转，直接返回
        } catch (e: Exception) {
            // 跳转失败，继续尝试跳转到 Google Play
        }
    }

    // 如果 CHIHI App Store 不存在或者跳转失败，使用 Google Play
    try {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$this"))
        intent.setPackage("com.android.vending")
        context.startActivity(intent)
    } catch (e: Exception) {
        // 如果 Google Play Store 不存在或者跳转失败，使用 Web 浏览器打开
        val intent = Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://play.google.com/store/apps/details?id=$this")
        )
        context.startActivity(intent)
    }
}

fun List<HomeChannelDto>.updateChannelList() {
    val localChannels = AppCache.channelList.associateBy { it.packageName }

    // 创建新的频道列表
    val newChannels = this
        .groupBy { it.packageName }
        .map { (packageName, homeChannels) ->
            val existingChannel = localChannels[packageName]

            if (existingChannel != null) {
                // 合并已存在的channelDataList
                val mergedChannelData = homeChannels.mapNotNull { homeChannel ->
                    homeChannel.channelName?.let { channelName ->
                        // 查找本地已存在的channelData
                        val existingData = existingChannel.channelDataList.find {
                            it.channelName == channelName
                        }

                        existingData ?: ChanelData(
                            channelName = channelName,
                            isShowChannelData = true,
                            channelId = homeChannel.channelId
                        )
                    }
                }.toMutableList()

                existingChannel.apply {
                    channelDataList = mergedChannelData
                }
            } else {
                // 新建CusChanelDto
                CusChanelDto(
                    appName = packageName?.getAppNameWithCache().toString(),
                    packageName = packageName ?: "",
                    desc = "",
                    channelDataList = homeChannels.mapNotNull { homeChannel ->
                        homeChannel.channelName?.let { channelName ->
                            ChanelData(
                                channelName = channelName,
                                isShowChannelData = true,
                                channelId = homeChannel.channelId
                            )
                        }
                    }.toMutableList()
                )
            }
        }

    // 移除不存在的packageName
    val existingPackageNames = this.mapNotNull { it.packageName }.toSet()
    val filteredChannels = AppCache.channelList.filter { it.packageName in existingPackageNames }

    // 更新AppCache.channelList
    AppCache.channelList = (filteredChannels + newChannels)
        .distinctBy { it.packageName }
        .toMutableList()
}

fun saveHomeParentDto(){
    val list = mutableListOf<HomeParentDto>()
    TvRepository.getChannelData().forEach {
        list.add(
            HomeParentDto(
                it.channelName.toString(),
                it.channelId ?: 0,
                recommondInfoDtoList = it.programList,
                packageName = it.packageName?:""
            )
        )
    }
    AppCache.homeParentList = list
}

fun getFilteredChannelsEnhanced(): List<HomeChannelDto> {
    val localChannels = AppCache.channelList.associateBy { it.packageName }

    // 获取最新的频道数据
    val newChannels = TvRepository.getChannelData()

    // 当本地频道列表为空时，直接更新缓存并返回所有新数据
    if (localChannels.isEmpty()) {
        AppCache.channelList = newChannels.map { homeChannel ->
            CusChanelDto(
                appName = homeChannel.packageName?.getAppNameWithCache().toString(),
                packageName = homeChannel.packageName ?: "",
                desc = "",
                channelDataList = mutableListOf(
                    ChanelData(
                        channelName = homeChannel.channelName ?: "",
                        isShowChannelData = true, // 新数据默认显示
                        channelId = homeChannel.channelId
                    )
                )
            )
        }.toMutableList()
        return newChannels
    }

    // 更新缓存并构建过滤后的结果
    val updatedChannels = newChannels.mapNotNull { homeChannel ->
        homeChannel.packageName?.let { pkg ->
            homeChannel.channelName?.let { name ->
                val existingChannel = localChannels[pkg]
                val existingChannelData = existingChannel?.channelDataList?.find {
                    it.channelName == name && it.channelId == homeChannel.channelId
                }

                // 构建新的ChanelData，保留isShowChannelData
                val newChannelData = ChanelData(
                    channelName = name,
                    isShowChannelData = existingChannelData?.isShowChannelData ?: true,
                    channelId = homeChannel.channelId
                )

                // 更新或创建CusChanelDto
                if (existingChannel != null) {
                    // 更新已有packageName的channelDataList
                    val updatedChannelDataList = existingChannel.channelDataList.toMutableList().apply {
                        val index = indexOfFirst { it.channelName == name && it.channelId == homeChannel.channelId }
                        if (index >= 0) {
                            set(index, newChannelData)
                        } else {
                            add(newChannelData)
                        }
                    }
                    existingChannel.copy(channelDataList = updatedChannelDataList)
                } else {
                    // 新建CusChanelDto
                    CusChanelDto(
                        appName = pkg.getAppNameWithCache().toString(),
                        packageName = pkg,
                        desc = "",
                        channelDataList = mutableListOf(newChannelData)
                    )
                }
            }
        }
    }

    // 更新AppCache.channelList
    AppCache.channelList = updatedChannels.toMutableList()

    // 返回过滤后的数据，保留原过滤逻辑
    return newChannels.filter { homeChannel ->
        homeChannel.packageName?.let { pkg ->
            homeChannel.channelName?.let { name ->
                updatedChannels
                    .find { it.packageName == pkg }
                    ?.channelDataList
                    ?.filter { it.isShowChannelData }
                    ?.any { it.channelName == name } == true
            } == true
        } == true
    }
}


fun MutableStateFlow<AppTask>.localCheck(): MutableStateFlow<AppTask> {
    val task = this.value
    val isInstalled = try {
        appContext.packageManager.getPackageInfo(task.businessId, 0)
        true
    } catch (_: Exception) {
        false
    }
    //println("当前的isInstalled是----$isInstalled-----包名是：${task.businessId}")
    val file = File(task.filePath)
    val fileExists = file.exists()

    when {
        isInstalled -> {
            if (task.versionCode != null && task.versionCode > 0) {
                val isSameVersionInstalled =
                    appContext.isSameVersionInstalled(task.businessId, task.versionCode.toInt())
               // println("是否是同一个版本：$isSameVersionInstalled----${task.businessId}----${task.versionCode}")
                if (isSameVersionInstalled) {
                    this.update { it.copy(status = AppTaskStatus.INSTALLED) }
                }
            } else {
                //println("只是本地已安装")
                this.update { it.copy(status = AppTaskStatus.INSTALLED) }
            }

        }

        task.status == AppTaskStatus.INSTALLED && !isInstalled -> {
            this.update { it.copy(status = AppTaskStatus.PENDING) }
        }

        task.status == AppTaskStatus.PENDING && fileExists -> {
            this.update { it.copy(status = AppTaskStatus.DOWNLOAD_COMPLETED) }
        }

        else -> {}
    }

    return this
}

fun String.launchCommonPanelAtvActivity(vararg extras: Pair<String, Any>) {
    val context = currentActivity as? FragmentActivity ?: return
    context.startKtxActivity<CommonPanelActivity>(
        values = arrayOf<Pair<String, Any>>(
            CommonPanelActivity.TYPE to this,
            *extras
        )
    )
}